<template>
  <div ref="chartRef" :style="{ width: '100%', height: height }"></div>
</template>

<script setup>
import { onMounted, watch, ref, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: Array,
  height: { type: String, default: '500px' },
  barColor: { type: String, default: '#5470C6' },
  yAxisField: { type: String, default: 'name' }  // 控制纵坐标用哪个字段
})

const chartRef = ref(null)
let chartInstance = null

const renderChart = (data, title, barColor, yAxisField) => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  const yAxisData = data.map(item => item[yAxisField] || '')

  const option = {
    title: { text: title },
    tooltip: {
      formatter: params => {
        return `${params.name}<br/>开始：${params.data.start}<br/>结束：${params.data.end}`
      }
    },
    xAxis: {
      type: 'time',
      axisLabel: { formatter: val => new Date(val).toLocaleDateString() }
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item[props.yAxisField] || '')
    },
    series: [
      {
        type: 'custom',
        renderItem(params, api) {
          const categoryIndex = api.value(0)
          const start = api.coord([api.value(1), categoryIndex])
          const end = api.coord([api.value(2), categoryIndex])
          const height = 20

          return {
            type: 'rect',
            shape: {
              x: start[0],
              y: start[1] - height / 2,
              width: end[0] - start[0],
              height: height
            },
            style: { fill: barColor }
          }
        },
        encode: { x: [1, 2], y: 0 },
        data: data.map((item, index) => ({
          value: [
            index,
            +new Date(item.start_time),
            +new Date(item.end_time)
          ],
          name: item.name,
          start: item.start_time,
          end: item.end_time
        }))
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    renderChart(props.data, props.title, props.barColor, props.yAxisField)
  })
})

watch(() => [props.data, props.yAxisField], ([newData, newField]) => {
  renderChart(newData, props.title, props.barColor, newField)
}, { deep: true })

onBeforeUnmount(() => {
  chartInstance?.dispose()
})
</script>
